package nl.stroep.classbuilder.codeformatter 
{
	/**
	 * CodeFormatter util
	 * @author Mark Knol - Stroep.nl - 2010 (c)
	 */
	public class CodeFormatter
	{
		public function CodeFormatter() 
		{
			throw new Error("Cannot create instance of CodeFormatter. Use static functions instead.")
		}
		
		/// Format code for nice output
		public static function format(value:String):String
		{
			// remove double spaces
			value = value.split("  ").join(" "); 
			
			// remove tabs
			value = value.split("\t").join(""); 
			
			// remove newlines
			value = value.split("\r").join(""); 
			value = value.split("\n\n").join("\n"); 

			// reset curly brackets
			value = value.split("{ ").join("{"); 
			value = value.split("} ").join("}");
			value = value.split("\n}").join("}");
			value = value.split("}\n").join("}");
			value = value.split("{\n").join("{"); 
			value = value.split("\n{").join("{"); 
			value = value.split("{").join("\n{\n"); 
			value = value.split("}").join("\n}\n\n"); 
			
			return indent(value);
		}
		
		/// Indent code using tabs
		public static function indent(value:String):String
		{
			var retval:String = value;
			
			var level:int = 0;
			
			var list:Array = retval.split("\n");
			
			for (var i:int = 0; i < list.length; ++i) 
			{
				if (String(list[i]).indexOf("}") > -1)
				{
					level --
				}
				
				list[i] = getTabs(level) + String(list[i]);
				
				if (String(list[i]).indexOf("{") > -1)
				{
					level ++				
				}
			}
			return list.join("\n");
		}
		
		private static function getTabs(level:int):String
		{
			var tabs:String = "";
			for (var t:int = 0; t < level; ++t) 
			{
				tabs += "\t";
			}
			return tabs;
		}
	}

}